package com.tencent.txcc.mq;

import com.alibaba.fastjson.JSON;
import com.tencent.txcc.domain.CourseOrder;
import com.tencent.txcc.dto.PayDto;
import com.tencent.txcc.enums.GlobleExceptionCode;
import com.tencent.txcc.service.ICourseOrderService;
import com.tencent.txcc.util.AssertUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Slf4j
@Component
@RocketMQTransactionListener(txProducerGroup="order-group")
public class Listen implements RocketMQLocalTransactionListener {

    @Autowired
    private ICourseOrderService courseOrderService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) {
        try {
            log.info("开始执行本地事务");
            // 判断传入的参数是否为空
            AssertUtil.isNotNull(arg, GlobleExceptionCode.PARAM_IS_NULL);
            // 通过订单号查询是否下单成功，找出来对象就说明已经下单了，没找出来则说明没有下单，执行下单流程

            // 将arg转为JSON对象
            CourseOrder courseOrder = JSON.parseObject(arg.toString(), CourseOrder.class);

            // 防止并发线程不安全，枷锁
            synchronized (courseOrder.getOrderNo()){
                // 如果没有获取到数据库中有值，则执行下单业务
                if (courseOrderService.selectByOrderNo(courseOrder.getOrderNo()) == null){
                    courseOrderService.addCourseOrderAndCourseOrderItem(courseOrder);
                    log.info("本地事务执行成功");
                    return RocketMQLocalTransactionState.COMMIT;
                } else {
                    log.info("本地事务执行失败");
                    return RocketMQLocalTransactionState.ROLLBACK;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("本地事务执行异常");
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        try {
            // 强转为byte[]
            byte[] bytes = (byte[]) message.getPayload();
            // 将bytes转为字符串再转为JSON对象
            String str = new String(bytes, StandardCharsets.UTF_8);
            PayDto payDto = JSON.parseObject(str, PayDto.class);
            // 判断对象是否为空，如果为空则说明对象没有消息传过来，直接回滚
            if (payDto == null){
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            // 判断是否有该订单，如果有，则说明本地事务成功，如果没有则说明本地事务执行失败
            if (courseOrderService.selectByOrderNo(payDto.getOrderNo()) == null){
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

}
